#include "app_mqtt.h"
#include "MQTTClient.h"
#include "log/log.h"
#include <string.h>

#define ADDRESS "ws://192.168.16.23:1883"
#define CLIENTID "b253ba38-daf6-4b37-984f-5d8fdc6a1cwd"
#define TOPIC_RTG "remote_to_gateway"
#define TOPIC_GTR "gateway_to_remote"
#define QOS 1
#define TIMEOUT 10000L

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static int rc;
// 发布消息
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 定义接收处理消息数据的回调函数指针
static int (*recv_callback)(char *data) = NULL;

// 发送完成
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("Message delivered");
}

// 接收消息 1表示接收成功 0表示接收失败
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int ret = 0;
    if (recv_callback != NULL)
    {
        ret = (recv_callback((char *)message->payload) == 0 ? 1 : 0);
    }
    // 释放内存
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return ret;
}

// 连接丢失
static void connlost(void *context, char *cause)
{
    log_debug("Connection lost: %s", cause);
}

int app_mqtt_init(void)
{
    // 创建MQTTClient实例
    rc = MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_debug("mqtt create error return code: %d", rc);
        return -1;
    }

    // 设置回调函数
    rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_debug("mqtt set callback error return code: %d", rc);
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接到MQTT服务器
    rc = MQTTClient_connect(client, &conn_opts);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_debug("mqtt connect error return code: %d", rc);
        MQTTClient_destroy(&client);
        return -1;
    }

    // 订阅主题
    rc = MQTTClient_subscribe(client, TOPIC_RTG, QOS);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_debug("mqtt subscribe error return code: %d", rc);
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }

    log_debug("mqtt init success");

    return 0;
}

void app_mqtt_close(void)
{
    // 取消订阅
    MQTTClient_unsubscribe(client, TOPIC_RTG);
    // 断开连接
    MQTTClient_disconnect(client, TIMEOUT);
    // 销毁实例
    MQTTClient_destroy(&client);
}

int app_mqtt_publish(char *data)
{
    pubmsg.payload = data;
    pubmsg.payloadlen = strlen(data);
    pubmsg.qos = QOS;
    rc = MQTTClient_publishMessage(client, TOPIC_GTR, &pubmsg, NULL);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        log_debug("mqtt publish error return code: %d", rc);
        return -1;
    }
    log_debug("mqtt publish success");
    return 0;
}

void app_mqtt_registerRecvCallback(int (*callback)(char *))
{
    recv_callback = callback;
}
